#include "stdafx.h"
#include "StopWatchImpl.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

using namespace boost::posix_time;
using namespace boost::gregorian;

namespace reckon {

	namespace util {

		RECKON_API StopWatch createStopWatch(IStopWatch::Type sw_type)
		{
			return StopWatch(new StopWatchImpl(sw_type));
		}

	}

	StopWatchImpl::StopWatchImpl(IStopWatch::Type t)
		: _refTime(microsec_clock::universal_time())
		, _sumSpanTime(0.)
		, _den(0)
	{
		switch (t)
		{
		case IStopWatch::seconds:		_den = 1.e+009;	break;
		case IStopWatch::milliseconds:	_den = 1.e+006;	break;
		case IStopWatch::microseconds:	_den = 1.e+003;	break;
		case IStopWatch::nanoseconds:	_den = 1.e+000;	break;
		default:						_den = 1.e+009;	break;
		}

		initTime();
	}

	StopWatchImpl::~StopWatchImpl()
	{
	}

	void StopWatchImpl::initTime()
	{
		_sumSpanTime = 0.;
		_refTime = microsec_clock::universal_time();
	}


	f64 StopWatchImpl::spanTime()
	{
		ptime current = microsec_clock::universal_time();

		time_duration span = current - _refTime;

		f64 ret = span.total_nanoseconds() / _den;

		_refTime = current;
		_sumSpanTime += ret;

		return ret;
	}

	f64 StopWatchImpl::totalSpanTime(bool bCallSpanTime)
	{
		if (bCallSpanTime)
			spanTime();

		return _sumSpanTime;
	}

} // namespace reckon